#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define DEF_PAGER "/bin/more"
#define MAXLINE 4096

void exitPrint(const char *str);
void exitPrint(const char *str){
        printf("%s\n", str);
        exit(0);
}

int main(int argc, char **argv){
    int n;
    int fd[2];
    pid_t pid;
    char *pager, *argv0;
    char line[MAXLINE];
    FILE *fp;

    if(argc != 2){
        exitPrint("usage: a.out <pathname>");
    }

    if((fp = fopen(argv[1], "r")) == NULL){
        exitPrint("fopen error");
    }
    if(pipe(fd) < 0){
        exitPrint("pipe error");
    }

    if((pid = fork()) < 0){
        exitPrint("fork error");
    }else if(pid > 0){
        close(fd[0]);

        while(fgets(line, MAXLINE, fp) != NULL){
            n = strlen(line);
            if(write(fd[1], line, n) != n){
                printf("%s\n", strerror(errno));

                exitPrint("write error");
            }
        }

        if(ferror(fp)){
            exitPrint("fgets error");
        }
        close(fd[1]);
        if(waitpid(pid, NULL, 0) < 0){
            exitPrint("waitpid error");
        }
        exit(0);
    }else{
        close(fd[1]);
        if(fd[0] != STDIN_FILENO){
            //复制STDIN_FILENO为fd[0]
            if(dup2(fd[0], STDIN_FILENO) < 0){
                exitPrint("dup2");
            }
            //接下来从标准输入读就行
            close(fd[0]);

            if((pager = getenv("PAGER")) == NULL){
                pager = DEF_PAGER;
            }
            if((argv0 = strchr(pager, '/')) != NULL){
                argv0++;
            }else{
                argv0 = pager;
            }

            if(execl(pager, argv0, NULL) < 0){
                exitPrint("execl error");
            }
        }
    }
}